package com.gack.business.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gack.business.dao.FKBDao;
import com.gack.business.dao.UserDao;
import com.gack.business.fkbModel.input.PushInput;
import com.gack.business.fkbModel.output.DepartmentOutputData;
import com.gack.business.fkbModel.output.EnterpriseOutputData;
import com.gack.business.fkbModel.output.PeopleOutputData;
import com.gack.business.fkbModel.output.PositionOutputData;
import com.gack.business.model.Message;
import com.gack.business.repository.DepartmentRepository;
import com.gack.business.repository.MessageRepository;
import com.gack.helper.common.util.JPushRestAPI;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * 费控宝接口(被费控宝调用)的service层
 * @author ws
 * 2018-7-18
 */
@Service
@Transactional
public class FKBService implements FKBServiceInterface{

	@Autowired
	private FKBDao fkbDao;
	@Autowired
	private DepartmentRepository departmentRepository;
	@Autowired
	private UserDao userDao;
	@Autowired
	private MessageRepository messageRepository;
	
	/**
	 * 公司查询(若orgcode为空,则查询所有公司;否则,查询指定id的公司)
	 * @param orgcode 公司id 可为空
	 * @return
	 */
	@Override
	public List<EnterpriseOutputData> findEnterprise(String orgcode) {
		
		//若公司id为空或空串,则查询所有公司信息(包含已删除公司)
		if(orgcode == null || orgcode.trim().length() == 0){
			return fkbDao.findAllEnterprise();
		}
		
		//若公司id不为空,则查询该公司信息
		return fkbDao.findEnterpriseById(orgcode);
	}

	
	/**
	 * 部门查询(若deptcode为空,则查询公司下所有部门;否则,查询指定部门信息及其子部门信息)
	 * @param orgcode 公司id 不可为空
	 * @param deptcode 部门id 可为空
	 * @return
	 */
	@Override
	public List<DepartmentOutputData> findDepartment(String orgcode, String deptcode) {
		
		//若部门id为空或空串,则查询公司下所有部门信息(包含已删除部门)
		if(deptcode == null || deptcode.trim().length() == 0){
			return fkbDao.findDepartmentByEnterpriseId(orgcode);
		}
	
		//若部门id不为空,则查询该部门信息及子部门信息
		List<String> departmentIds = findAllSubDepartmentId(orgcode, deptcode);
		departmentIds.add(deptcode);
		return fkbDao.findDepartmentByDepartmentIds(departmentIds);
	}
	
	/**
	 * 职位职级查询
	 * @param orgcode 公司id
	 * @return
	 */
	@Override
	public List<PositionOutputData> findPosition(String orgcode){
		return fkbDao.findPositionByEnterpriseId(orgcode);
	}
	
	/**
	 * 人员信息查询
	 * 情况①：若部门编码为空，人员编码为空，则返回指定公司下所有人员信息
	 * 情况②：若部门编码不为空，人员编码为空，则返回指定部门下所有人员信息(包括子部门人员信息)
	 * 情况③：若部门编码为空，人员编码不为空，则返回指定公司下指定人员信息
	 * 情况④：若部门编码不为空，人员编码不为空，则返回指定部门下指定人员信息
	 * @param orgcode 公司id 不可为空
	 * @param deptcode 部门id 可为空
	 * @param peoplecode 人员id 可为空
	 * @return
	 */
	@Override
	public List<PeopleOutputData> findPeople(String orgcode, String deptcode, String peoplecode) {
		
		//情况①：若部门编码为空，人员编码为空，则返回指定公司下所有人员信息
		if((deptcode == null || deptcode.trim().length() == 0) && (peoplecode == null || peoplecode.trim().length() == 0)){
			return fkbDao.findPeopleByEnterpriseId(orgcode);
		}
		
		//情况②：若部门编码不为空，人员编码为空，则返回指定部门下所有人员信息(包括子部门人员信息)
		if(deptcode != null && deptcode.trim().length() != 0 && (peoplecode == null || peoplecode.trim().length() == 0)){
			//查询该部门信息及子部门信息
			List<String> departmentIds = findAllSubDepartmentId(orgcode, deptcode);
			departmentIds.add(deptcode);
			return fkbDao.findPeopleByEnterpriseIdAndDepartmentId(orgcode, departmentIds);
		}
		
		//情况③：若部门编码为空，人员编码不为空，则返回指定公司下指定人员信息
		if((deptcode == null || deptcode.trim().length() == 0) && peoplecode != null && peoplecode.trim().length() != 0){
			return fkbDao.findPeopleByEnterpriseIdAndUserId(orgcode, peoplecode);
		}
		
		//情况④：若部门编码不为空，人员编码不为空，则返回指定部门下指定人员信息
		if(deptcode != null && deptcode.trim().length() != 0 && peoplecode != null && peoplecode.trim().length() != 0){
			//查询该部门信息及子部门信息
			List<String> departmentIds = findAllSubDepartmentId(orgcode, deptcode);
			departmentIds.add(deptcode);
			return fkbDao.findPeopleByEnterpriseIdAndUserId(orgcode, departmentIds, peoplecode);
		}
		
		return null;
	}
	
	/**
	 * 移动消息推送
	 * @param operatorNo 通知对象(人员登录名，多个用逗号隔开)
	 * @param remarks 通知内容
	 * @param H5url 手机端入口链接
	 * @param PCurl PC端入口链接
	 * @param type 1.审批提醒 2.消息提醒 3.其他
	 */
	@Override
	public net.sf.json.JSONObject pushMessage(String operatorNo, String remarks, String H5url, String PCurl, String type){
		String[] usernames = operatorNo.split(",");
		
		JPushRestAPI jPushRestAPI = new JPushRestAPI();
		List<String> list = new ArrayList<>();
		for(String t : usernames){
			list.add(t);
		}
		jPushRestAPI.setApns_production(false);
		PushInput.PushInputData model  = new PushInput.PushInputData();
		model.setOperatorNo(operatorNo);
		model.setRemarks(remarks);
		model.setH5url(H5url);
		model.setPCurl(PCurl);
		model.setType(type);
		
		net.sf.json.JSONObject result = jPushRestAPI.SendPush(remarks, "fkbPush", model, "Default", jPushRestAPI.jsonDataByManyAlias(list));
		if(!result.containsKey("error")){//若推送成功则保存message,否则不保存
			savePushMessage(list, remarks, H5url, PCurl, type);
		}
		
		return result;
	}
	
	/**
	 * 保存移动消息推送到message中
	 * @param usernames 手机号集合
	 * @param remarks 通知内容
	 * @param H5url 手机端入口链接
	 * @param PCurl PC端入口链接
	 * @param type 1.审批提醒 2.消息提醒 3.其他
	 */
	private void savePushMessage(List<String> usernames, String remarks, String h5url, String pcurl, String type){
		List<String> userIdList = userDao.findIdByUsername(usernames);
		for(String element : userIdList){
			Message message = new Message();
			message.setUserid(element);
			FKBService.PushContent pushContent = new FKBService.PushContent(remarks, h5url, pcurl, type);
			message.setMessage(com.alibaba.fastjson.JSONObject.toJSONString(pushContent));
			message.setCreatetime(new Date());
			message.setTitle("费控宝推送消息");
			message.setMesType(7);
			message.setSendWay(2);
			message.setIsRead(0);
			messageRepository.save(message);
		}
	}

	@Getter
	@Setter
	@NoArgsConstructor
	@AllArgsConstructor
	private static class PushContent{
		private String remarks;
		private String h5url;
		private String pcurl;
		private String type;
	}
	
	/**
	 * 获取某部门下所有子部门id(全部子部门包含：层层嵌套子部门,包含已删除部门)
	 * @param departmentId 部门id
	 * @return
	 */
	public List<String> findAllSubDepartmentId(String enterpriseId, String departmentId){
		List<String> allSubDepartmentIdList = new ArrayList<>();
		
		if(departmentId == null || departmentId.trim().length() == 0){
			return allSubDepartmentIdList;
		}
		
		List<String> subDepartmentIdList = departmentRepository.findNextSubDepartmentIdIncludeDeletedByDepartmentId(enterpriseId, departmentId);
		allSubDepartmentIdList.addAll(subDepartmentIdList);
		while(subDepartmentIdList != null && subDepartmentIdList.size() != 0){
			List<String> subTemp = null;
			Iterator<String> it = subDepartmentIdList.iterator();
			if(it.hasNext()){
				String t = it.next();
				subTemp = departmentRepository.findNextSubDepartmentIdIncludeDeletedByDepartmentId(enterpriseId, t);
				it.remove();
			}
			if(subTemp != null && subTemp.size() != 0){
				subDepartmentIdList.addAll(subTemp);
				allSubDepartmentIdList.addAll(subTemp);
			}
		}
		
		return allSubDepartmentIdList;
	}
}
